package com.knowledge.plus.java8;

import com.knowledge.plus.java8.pojo.Java8Message;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author TPF
 * @since 2023/2/15
 */
public class 集合按某字段去重 {

    @Test
    public void removalRepeatList() {
        List<Java8Message> java8MessageList = Java8Message.getMessageList();
        java8MessageList.add(new Java8Message(1, "aaa", new Date()));
        java8MessageList.add(new Java8Message(2, "bbb", new Date()));
        java8MessageList.add(new Java8Message(4, "bbb", new Date()));
        java8MessageList.add(new Java8Message(3, "ccc", new Date()));
        java8MessageList.add(new Java8Message(2, "eee", new Date()));
        java8MessageList.add(new Java8Message(3, "fff", new Date()));
        java8MessageList.add(new Java8Message(5, "ggg", new Date()));

        /** 按 id 去重排序，完整写法 */
        ArrayList<Java8Message> collect = java8MessageList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Java8Message::getId))), ArrayList::new));
        System.out.println(collect.size());

        /** 拆分 */
        // 1. 首先使用Collectors.toCollection()方法创建了一个TreeSet集合，TreeSet本身具有去重和排序的功能
        Collector<Java8Message, ?, TreeSet<Java8Message>> messageTreeSetCollector
                = Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Java8Message::getId)));

        // 2. 将TreeSet集合转换为ArrayList集合
        // Collectors.collectingAndThen() 是Java 8中的一个辅助方法，它能够将一个 Collector 收集器转换为另一个收集器，并在最终收集结果上应用一个Function函数
        ArrayList<Java8Message> collect2 = java8MessageList.stream()
                .collect(Collectors.collectingAndThen(messageTreeSetCollector, ArrayList::new));

        System.out.println(collect2.size());
    }

}
